package com.rdc.example.service.impl;

import com.rdc.example.bean.Result;
import com.rdc.example.bean.dto.ArticleDTO;
import com.rdc.example.dao.ArticleDao;
import com.rdc.example.dao.LikeDao;
import com.rdc.example.dao.impl.ArticleDaoImpl;
import com.rdc.example.dao.impl.LikeDaoImpl;

import java.util.List;

/**
 * @author duck
 */
public class LikeServiceImpl implements com.rdc.example.service.LikeService {
    LikeDao likeDao = new LikeDaoImpl();

    /**
     *
     * @param userId
     * @param articleId
     * @return
     * @throws Exception
     */
    @Override
    public Result turnLike(Integer userId, Integer articleId) throws Exception {
        try {
            if (userId == null || articleId == null) {
                return null;
            }
            ArticleDao articleDao = new ArticleDaoImpl();
            if(likeDao.likeCheck(userId, articleId)) {
                //点赞了，取消,article.Like--
                boolean registerLike =likeDao.deleteLike(userId, articleId);
                boolean registerArticle=articleDao.reduceLike(articleId);
                return registerLike&&registerArticle ? Result.success("取消成功", null)
                                             : Result.fail("取消失败", null);
            }else {
                //没点赞，要点,article.Like++
                boolean registerLike =likeDao.insertLike(userId, articleId);
                boolean registerArticle=articleDao.addLike(articleId);
                return registerLike&&registerArticle ? Result.success("点赞成功", null)
                        : Result.fail("点赞失败", null);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     *
     * @param userId
     * @return
     * @throws Exception
     */
    @Override
    public List<ArticleDTO> getLikeArticlesListByUserId(Integer userId) throws Exception {
        try {
            if (userId == null) {
                return null;
            }
            List<Integer> articleIds =likeDao.listArticleIdByUserId(userId);
            ArticleServiceImpl articleService = new ArticleServiceImpl();
            return articleService.listArticleByIds(articleIds);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
